﻿mainModule.controller("articleListCtrl", ["$scope", "$rootScope", "articleSvc", "notification", "pageState", "$location", "cache", function ($scope, $rootScope, articleSvc, notification, pageState, $location, cache) {
    var query = {};
    $scope.selectedIndex = 0;
    
    findBy(query).then(function () {
        routeToItems();
    });
    
    function findBy(query) {
        return articleSvc.findNamesBy(query).then(function (response) {            
            $scope.list = response.data.List;
        });
    }

    function routeToItems(index) {
        if (typeof (index) == "undefined")
            index = $scope.selectedIndex;

        var url = "";
        var article = $scope.list[index];
        if (typeof (article) !== "undefined") {            
            if (article.TypeID === 1)
                url = "/sitems/"
            else
                url = "/titems/";

            $location.path(url + article.ID);
            currentArticleID = article.ID;            
        }
        else {
            $location.path("/empty");            
        }
    }

    $scope.remove = function (index, event) {
        var article = $scope.list[index];
        articleSvc.remove(article.ID).then(function (response) {
            if (response.data.Success) {
                $scope.list.splice(index, 1);
                cache.remove("/api/articleapi/" + article.ID);                
                $scope.selectedIndex = 0;
                routeToItems(0);
            }
            notification.notify(response.data);
        });

        event.stopPropagation();
    }

    $scope.select = function (index) {        
        $scope.selectedIndex = index;
        routeToItems();
    }

    $scope.activate = function (index) {
        $scope.activeIndex = index;     
    }

    $scope.deactivate = function (index) {
        if ($scope.activeIndex == index)
            $scope.activeIndex = -1;        
    }

    $scope.edit = function (index, event) {
        $scope.selectedIndex = index;
        event.stopPropagation();
    }

    $scope.$on('articleAdded', function (e, item) {       
        $scope.list.push(item);
        $scope.selectedIndex = $scope.list.length -1;
    });

    $scope.$on('articleEdited', function (e, item) {        
        $scope.list[$scope.selectedIndex] = item;
    });
        
}]);




